<?php
use think\Db;

// 应用公共文件
define('HB_VERSION','1.0' );
/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'...' : $slice;
}
/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function hb_member_md5($str, $key = 'HuiboMember'){
	return '' === $str ? '' : md5(sha1($str) . $key);
}
/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author wapai   邮箱:zipzty@gmail.com
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
function time_nianyueri($time = NULL,$format='Y-m-d'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
function time_nianyue($time = NULL,$format='Y-m'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
function time_nian($time = NULL,$format='Y'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
function time_yueri($time = NULL,$format='m-d'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
function time_yue($time = NULL,$format='m'){
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 */
function get_client_ip($type = 0, $adv = false) {
    $type      = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }

            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
     } if(is_array($array)) {
         foreach($array as $key=>$value) {
             $array[$key] = object_array($value);
             }
     }
     return $array;
}
function site_root(){
    $root  = $phpfile = '';
    $iscgi = (0 === strpos(PHP_SAPI,'cgi') || false !== strpos(PHP_SAPI,'fcgi')) ? 1 : 0 ;
    if ( $iscgi ) {
      $temp    = explode('.php',$_SERVER['PHP_SELF']);
      $phpfile = rtrim(str_replace($_SERVER['HTTP_HOST'],'',$temp[0].'.php'),'/');
    } else {
      $phpfile = rtrim($_SERVER['SCRIPT_NAME'],'/');
    }
    $root =   rtrim(dirname($phpfile),'/');
    return (($root=='/' || $root=='\\') ? '' : $root);
 }

 function getExtendFileName($file_name) {

     $extend = pathinfo($file_name);
     $extend = strtolower($extend["extension"]);
     return $extend;
 }

 function extractImageFromWorksheet($worksheet,$basePath){

     $result = array();

     $imageFileName = "";

     foreach ($worksheet->getDrawingCollection() as $drawing) {
         $xy=$drawing->getCoordinates();
         $path = $basePath;
         // for xlsx
         if ($drawing instanceof PHPExcel_Worksheet_Drawing) {

             $filename = $drawing->getPath();

             $imageFileName = $drawing->getIndexedFilename();

             $path = $path . $drawing->getIndexedFilename();

             copy($filename, $path);

             $result[$xy] = $path;

             // for xls
         } else if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {

             $image = $drawing->getImageResource();

             $renderingFunction = $drawing->getRenderingFunction();

             switch ($renderingFunction) {

                 case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:

                     $imageFileName = $drawing->getIndexedFilename();
                     $path = $path . $drawing->getIndexedFilename();
                     imagejpeg($image, $path);
                     break;

                 case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
                     $imageFileName = $drawing->getIndexedFilename();
                     $path = $path . $drawing->getIndexedFilename();
                     imagegif($image, $path);
                     break;

                 case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
                     $imageFileName = $drawing->getIndexedFilename();
                     $path = $path . $drawing->getIndexedFilename();
                     imagegif($image, $path);
                     break;

                 case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
                     $imageFileName = $drawing->getIndexedFilename();
                     $path = $path . $drawing->getIndexedFilename();
                     imagegif($image, $path);
                     break;
             }
             $result[$xy] = $imageFileName;
         }
     }

     return $result;
 }

 function excelTime($date, $time = false) {
        if (function_exists('GregorianToJD')) {
            if (is_numeric($date)) {
                $jd = GregorianToJD(1, 1, 1970);
                $gregorian = JDToGregorian($jd + intval($date) - 25569);
                $date = explode('/', $gregorian);
                $date_str = str_pad($date[2], 4, '0', STR_PAD_LEFT) . "-" . str_pad($date[0], 2, '0', STR_PAD_LEFT) . "-" . str_pad($date[1], 2, '0', STR_PAD_LEFT) . ($time ? " 00:00:00" : '');
                return $date_str;
            }
        } else {
            $date = $date > 25568 ? $date + 1 : 25569; /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/
            $ofs = (70 * 365 + 17 + 2) * 86400;
            $date = date("Y-m-d", ($date * 86400) - $ofs) . ($time ? " 00:00:00" : '');
        }
        return $date;
    }

    /**
     *  根据身份证号码获取性别
     *  author:xiaochuan
     *  @param string $idcard    身份证号码
     *  @return int $sex 性别 1男 2女 0未知
     */
    function get_sex($idcard) {
        if(empty($idcard)) return null;
        $sexint = (int) substr($idcard, 16, 1);
        return $sexint % 2 === 0 ? '女' : '男';
    }

    /**
     *  根据身份证号码获取生日
     *  author:xiaochuan
     *  @param string $idcard    身份证号码
     *  @return $birthday
     */
    function get_birthday($idcard) {
        if(empty($idcard)) return null;
        $bir = substr($idcard, 6, 8);
        $year = (int) substr($bir, 0, 4);
        $month = (int) substr($bir, 4, 2);
        $day = (int) substr($bir, 6, 2);
        return $year . "-" . $month . "-" . $day;
    }

    /**
     *  根据身份证号码计算年龄
     *  author:xiaochuan
     *  @param string $idcard    身份证号码
     *  @return int $age
     */
    function get_age($idcard){
        if(empty($idcard)) return null;
        #  获得出生年月日的时间戳
        $date = strtotime(substr($idcard,6,8));
        #  获得今日的时间戳
        $today = strtotime('today');
        #  得到两个日期相差的大体年数
        $diff = floor(($today-$date)/86400/365);
        #  strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age = strtotime(substr($idcard,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
        return $age;
    }

  function get_one_image($content,$order='ALL'){
          $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
          preg_match_all($pattern,$content,$match);
          if(isset($match[1])&&!empty($match[1])){
              if($order==='ALL'){
                  return $match[1][0];
              }
              if(is_numeric($order)&&isset($match[1][$order])){
                  return $match[1][$order];
              }
          }
          return '';
      }


function  get_actionlog($uid,$action,$title){
  $data['uid']=$uid;
  $data['name']=Db::name('Member')->where('id',$uid)->value('nickname');
  $data['action']=$action;
  $data['title']=$title;
  $data['create_time']=time();
  $ids=Db::name('Userlog')->insert($data);

}
function  get_danwei($id){
  if($id){
    $danwei=Db::name('Danwei')->where('id',$id)->value('name');
    return $danwei;
  }
}

function arraySequence($array, $field, $sort = 'SORT_DESC')
{
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;
}
function getRandTable($nums,$biao,$map){
   /* $num = 5;    //需要抽取的默认条数
    $table = 't_marclog';    //需要抽取的数据表*/
//    $countcus = Db::name($biao)->where($map)->count();    //获取总记录数
//    $min = Db::name($biao)->where($map)->min('id');    //统计某个字段最小数据
    $shudata=Db::name($biao)->where($map)->field('id')->select();
    if($shudata){
        $arrs=array();
        $countcus=-1;
        foreach ($shudata as $key=>$value){
            $arrs[]=$value['id'];
            $countcus++;
        }
        $min=0;

    $i = 1;
    $flag = 0;
    $ary = array();
    if($countcus==0){
        $ary[]=$arrs;
    }else{
    while($i<=$nums){
        $rundnum = rand($min, $countcus);//抽取随机数
        if($flag != $rundnum){
            //过滤重复
            if(!in_array($rundnum,$ary)){
                $ary[] =$arrs[$rundnum];
                $flag = $rundnum;
            }else{
                $i--;
            }
            $i++;
        }
    }
    }
    }
    return $ary;
}

function readrate($times,$uid){
  $ksdqtimes=strtotime(time_nianyueri($times));
  $enddqtimes=$ksdqtimes+86400;
  $kstimes=$ksdqtimes-(86400*30);
  $lushu=0;
  $day=0;
    for ($x=$kstimes; $x<=$enddqtimes;$x=$x+86400) {
        $kaishitime = $x;
        $jieshutime = $x + 86400;

        $cz=Db::name('Userlog')->where('uid',$uid)->where('create_time','between',[$kaishitime,$jieshutime])->find();
        if($cz){
            $lushu++;
        }
        unset($cz);
        $day++;
    }
    $SHUJU=floor(($lushu/$day)*100)/100;
    return $SHUJU;
}

/**
 * 返回带协议的域名
 * @return string 域名
 */
function sp_get_host(){
    $host = $_SERVER["HTTP_HOST"];
    $protocol = is_ssl()?"https://":"http://";
    return $protocol.$host;
}
/**
 * 获取所有的城镇村
 * @param $code
 * @return string
 */
function get_alltowns($code){
    if($code){
        $info=Db::name('Towns')->where('code',$code)->find();
        if($info){
            $infos=Db::name('Towns')->where('code',$info['pid'])->value('tname');
            return $infos.'-'.$info['tname'];
        }else{
            return 'error';
        }
    }else{
        return 'canshuerror';
    }
}
/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl() {
    if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
        return true;
    }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
        return true;
    }
    return false;
}

function trimall($str)//删除空格
{
    $oldchar=array(" ","　","\t","\n","\r");
    $newchar=array("","","","","");
    return str_replace($oldchar,$newchar,$str);
}
// 从内容中获取摘要
function getDescriptionFromContent($content='', $len=70)
{
    $content = strval($content);
    if (empty($content))
        return false;
    $content = preg_replace("@<script(.*?)</script>@is", "", $content);
    $content = preg_replace("@<iframe(.*?)</iframe>@is", "", $content);
    $content = preg_replace("@<style(.*?)</style>@is", "", $content);
    $content = preg_replace("/&nbsp;/", "", $content);
    $content = preg_replace("@<(.*?)>@is", "", $content);
    $content = str_replace(PHP_EOL, '', $content);
    $space = array(" ", "　", "  ", " ", " ");
    $go_away = array("", "", "", "", "");
    $content = str_replace($space, $go_away, $content);
    $res = mb_substr($content, 0, $len, 'UTF-8');
    if (mb_strlen($content, 'UTF-8') > $len) {
        $res = $res . "...";
    }
    return $res;
}
/**
 * 获取村镇名
 * @param $code
 * @return mixed|string
 */
function get_towns($code){
    if($code){
        $info=Db::name('Towns')->where('code',$code)->value('tname');
        if($info){
            return $info;
        }else{
            return 'error';
        }
    }else{
        return 'canshuerror';
    }
}